//
//  EndGameViewController.m
//  Politics
//
//  Created by Hai Nguyen on 7/9/11.
//  Copyright 2011 VinaSource. All rights reserved.
//

#import "EndGameViewController.h"
#import "MainViewController.h"
#import "AppDelegate_iPhone.h"
#import "FBPoster.h"
#import "FBSession.h"
#import "FBUtilities.h"
#import "TwitterPoster.h"
#import "HighScoreCell.h"

@implementation EndGameViewController

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/
- (IBAction)buttonPressed:(id)sender
{
	[Audio playButtonClicked];
	UIButton *button = (UIButton*) sender;
	switch (button.tag) {
		case 1:
		{
			FBSession *fbSession = [FBSession session];
			if (fbSession == nil)
			{
				[mainiPhoneAppDelegate.FButilities facebookLogin:self];
			}
			else if(fbSession.isConnected)
			{
				[self createFBPostDialog];
			}
			else
			{
				[mainiPhoneAppDelegate.FButilities facebookLogin:self];
			}
		}
			break;
		case 2:
			[mainiPhoneAppDelegate.twitter twit:[NSString stringWithFormat:@"I have scored %@ on Politics Game",pointValueLabel.text] withLink:@"http://politics.com/game" forapp:@"Politics Game" makeTiny:NO delegate:nil];
			break;
		case 3:
			[[[MainViewController mainViewController] mainMenuNavController] popToRootViewControllerAnimated:YES];
			break;
		case 4:
		{
			MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
			controller.mailComposeDelegate = self;
			[controller setSubject:@"Funny Game on iPhone"];
			[controller setMessageBody:@"I am playing Politics Game on iPhone, It's so fun" isHTML:NO]; 
			if (controller)
			{
				[self presentModalViewController:controller animated:YES];
			}
			[controller release];
		}
			break;

		default:
			break;
	}
}
#pragma mark - Message delegate
- (void)mailComposeController:(MFMailComposeViewController*)controller  
          didFinishWithResult:(MFMailComposeResult)result 
                        error:(NSError*)error;
{
	NSLog(@"dismis email composer");
	
	if (result == MFMailComposeResultSent) 
	{
		//NSLog(@"It's away!");
	}
	[self dismissModalViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark UITextView Delegate Methods
- (void)textViewDidEndEditing:(UITextView *)textView 
{
	[textView resignFirstResponder];
}
- (void) createFBPostDialog
{
	if(!fbMessageTextView)
	{
		fbMessageTextView = [[UITextView alloc] initWithFrame:CGRectMake(0,0,240,90)];
		//[fbMessageTextView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"textbox_background.png"]]];
		fbMessageTextView.editable = YES;
		fbMessageTextView.textColor = [UIColor blackColor];
		fbMessageTextView.font = [UIFont systemFontOfSize:15];
		fbMessageTextView.scrollEnabled = YES;
		//fbMessageTextView.backgroundColor = [UIColor clearColor];
		fbMessageTextView.delegate = self;
		fbMessageTextView.layer.cornerRadius = 5;
	}
	
	
	
	if([fbMessageTextView superview])
	{	
		[fbMessageTextView removeFromSuperview];		
	}
	
	fbMessageTextView.center = CGPointMake(140, 100);
	[fbMessageTextView setText:[NSString stringWithFormat:@"I have score %@ on Politics game",pointValueLabel.text]];
	
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Post to Wall" message:@"\n\n\n\n\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Post",nil];
	[alert addSubview:fbMessageTextView];
	[alert show];
	
	[alert release];
}
#pragma mark -
#pragma mark UIAlertView Delegate Methods
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
{
	if(buttonIndex == 0)
	{
		//Cancel
	}
	else
	{
		[FBPoster PostToWall:fbMessageTextView.text];
	}
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	highScoreArray = [[NSMutableArray alloc] init];
	[correctValueLabel setText:[NSString stringWithFormat:@"%d",mainiPhoneAppDelegate.numOfCorrect]];
	[incorrectValueLabel setText:[NSString stringWithFormat:@"%d",[mainiPhoneAppDelegate.arrayGames count] - mainiPhoneAppDelegate.numOfCorrect]];
	[pointValueLabel setText:[NSString stringWithFormat:@"%d",mainiPhoneAppDelegate.numOfCorrect]];
    [super viewDidLoad];
	ScoreSubmitParser *scoreSubmited = [[ScoreSubmitParser alloc] init];
	[scoreSubmited submitScore:mainiPhoneAppDelegate.username score:[pointValueLabel.text intValue] withDelegate:self];
	[scoreSubmited release];
	LoadHighScoreParser *loadHighScore = [[LoadHighScoreParser alloc] init];
	[loadHighScore getHighScoreList:self];
	[loadHighScore release];
}

#pragma mark -
#pragma mark ScoreSubmitParser Methods
- (void)didEndSubmit:(NSMutableArray*)result
{
	NSLog(@"Score Has Been Submited");
}
- (void)didEndLoadHighScore:(NSMutableArray*)resultArray
{
	NSLog(@"high score list %@",resultArray);
	[highScoreArray setArray:resultArray];
	if ([highScoreArray count]!=0)
	{
		NSDictionary *dict = [highScoreArray objectAtIndex:0];
		[highScoreValueLabel setText:[dict objectForKey:@"score"]];
	}
	[highScoreTable reloadData];
}
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
#pragma mark -
#pragma mark Table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [highScoreArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *cellId = @"highScoreCell";
	highScoreCell = (HighScoreCell*)[tableView dequeueReusableCellWithIdentifier:cellId];
	if (highScoreCell == nil) 
	{
		[[NSBundle mainBundle] loadNibNamed:@"HighScoreCell" owner:self options:nil];
	}
	NSDictionary *dict = [highScoreArray objectAtIndex:indexPath.row];
	[highScoreCell.nameLabel setText:[dict objectForKey:@"id"]];
	[highScoreCell.scoreLabel  setText:[dict objectForKey:@"score"]];
	[highScoreCell.indexLabel setText:[NSString stringWithFormat:@"%d",indexPath.row + 1]];
	return [highScoreCell autorelease];
	
}
- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}


@end
